library(dplyr)
library(tidyr)
library(ggplot2)

if (!file.exists("output")) {
  dir.create("output")
}

# load data
source("HNC_metadata_tidy.R")
source("data_handling.R")

cvCOSMIC <- read.csv("Input_signature_attributions/Input_CN_COSMIC_attributions.csv", stringsAsFactors = T) %>% rename(donor_id = X)

# CN clusters generated in Figure_7c.R
additional_df <- list(cvCOSMIC, CN_clusters <- read.csv("output/CN_clusters.csv"))

for (df in additional_df) {
  data <- data %>% left_join(df, by = "donor_id")
}

data <- data %>% filter(!is.na(HNC_clusters))

# Select signatures present in >n% of samples
# Dichotomize the signatures (Presence (signatures>0)="1",absence (signatures==0)="0")
# If signature is present in more than 75% cases, dichotomize by the median
data <- dichotomizeSigs(metadata = data, sigsn = cvCOSMIC, sigcutoff = 2)

for (sig in c("CN1", "CN2", "CN9", "CN12", "CN13", "CN18", "CN20")) {
  plot_kw(data, signatures = sig, factors = "HNC_clusters", pval_cutoff = 1, x_labs = "", y_labs = "Signature burden")
  ggsave(paste0("output/ExtendedDataFigure_10_", sig, "_", Sys.Date(), ".pdf"),
    device = "pdf",
    width = 3.5, height = 4, dpi = 700
  )
}

for (sig in c("CN5", "CNV_G")) {
  plot_kw(data,
    signatures = sig, factors = "k2",
    pval_cutoff = 1, x_labs = "", y_labs = "Signature burden"
  )
  ggsave(paste0("output/ExtendedDataFigure_10_", sig, "_", Sys.Date(), ".pdf"),
    device = "pdf",
    width = 3.5, height = 4, dpi = 700
  )
}
